import { ExclamationCircleOutlined } from "@ant-design/icons";
import styles from "@styles/components/modal/modal_user.module.less";

import { withRouter } from "react-router-dom";
import React, { useState, useEffect } from "react";
import { message, Modal, Form, Input } from "antd";
import Http from "@utils/api";
import { AES } from "@utils/crypto";
import cookie from "react-cookies";

const { confirm } = Modal;

function ModalBox({ history, modalbox, openCloseModal }) {
  const [form] = Form.useForm();
  const [userinfo, setUserinfo] = useState({});
  const [resetpwd, setResetpwd] = useState({});

  // 对象值为 true, 返回键名
  const fil = (obj) => {
    for (let i in obj) if (obj[i]) return i;
  };

  // 对象值 AES 加密解密
  const filAES = (obj, type) => {
    for (let i in obj)
      obj[i] = type ? AES.Encrypt(obj[i]) : AES.Decrypt(obj[i]);
    return obj;
  };

  // 成功返回信息提示
  const Success = (val) => message.success(val);

  // 失败返回信息提示
  const Error = (val) => message.error(val);

  // form 表单 li 样式
  const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 17 },
  };

  // 监听事件 - 执行信息查询 - 修改密码 - 退出登录
  useEffect(() => {
    if (modalbox.userInfo) {
      Http.getByUserId({}).then(({ data }) => {
        setUserinfo(data);
      });
    } else if (modalbox.resetpwd) {
      Http.updateUserPassword({ ...resetpwd }).then(({ code, message }) => {
        if (code === 200) {
          handleOk();
          Success(message);
        } else {
          Error(message);
        }
      });
    } else if (modalbox.signout) {
      confirm({
        title: "确认退出此账号?",
        icon: <ExclamationCircleOutlined />,
        content: "",
        okText: "确定",
        cancelText: "取消",
        onOk() {
          Http.getLogout().then(({ code, message }) => {
            if (code === 200) {
              Success(message);
              handleOk();
              cookie.remove("userInfo");
              history.replace("/login");
            } else {
              Error(message);
            }
          });
        },
        onCancel() {
          handleOk();
        },
      });
    }

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [modalbox.userInfo, modalbox.signout, resetpwd]);

  // 弹窗 "确定" 按钮事件
  const handleOk = () => {
    openCloseModal(fil(modalbox));
  };

  // 修改密码 "确定" 按钮事件
  const handleResetOk = () => {
    setResetpwd(filAES(form.getFieldsValue(), true));
  };

  // 关闭弹窗 "返回" 按钮事件
  const handleCancel = () => {
    openCloseModal(fil(modalbox));
  };

  return (
    <>
      <Modal
        title="个人信息"
        zIndex={10000}
        footer={null}
        visible={modalbox.userInfo}
        onOk={handleOk}
        onCancel={handleCancel}
        className={styles.modalbox}
        width={400}
      >
        <aside>
          <dl>
            <dt>头像:</dt>
            <dd>
              <img src={userinfo.headPortrait} alt="" />
              <p>点击修改头像</p>
            </dd>
          </dl>
          <dl>
            <dt>账号:</dt>
            <dd>{userinfo.userAccount}</dd>
          </dl>
          <dl>
            <dt>姓名:</dt>
            <dd>{userinfo.userName}</dd>
          </dl>
          <dl>
            <dt>手机号:</dt>
            <dd>{userinfo.userPhone}</dd>
          </dl>
          <dl>
            <dt>性别:</dt>
            <dd>{userinfo.modifier}</dd>
          </dl>
        </aside>
      </Modal>
      <Modal
        title="修改密码"
        okText="确认"
        cancelText="取消"
        zIndex={10000}
        visible={modalbox.resetpwd}
        onOk={handleResetOk}
        onCancel={handleCancel}
        className={styles.modalbox}
        width={400}
      >
        <aside>
          <Form
            form={form}
            name="resetpassword"
            className={styles.resetpassword}
            {...formItemLayout}
            scrollToFirstError
          >
            <Form.Item
              name="userOldPwd"
              label="旧密码："
              hasFeedback
              rules={[{ required: true, message: "请输入原密码!" }]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name="userPwd"
              label="新密码："
              hasFeedback
              rules={[{ required: true, message: "请输入新密码!" }]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name="userConfirmPwd"
              label="确认密码："
              dependencies={["userPwd"]}
              hasFeedback
              rules={[
                { required: true, message: "请确认您的密码!" },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue("userPwd") === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject("您输入的两个密码不匹配!");
                  },
                }),
              ]}
            >
              <Input.Password />
            </Form.Item>
          </Form>
        </aside>
      </Modal>
    </>
  );
}

export default withRouter(ModalBox);
